// 页面加载时检查 URL 参数，自动显示数据表格
// 优化DOMContentLoaded事件处理
document.addEventListener('DOMContentLoaded', function () {
    // 使用requestIdleCallback处理非关键任务
    requestIdleCallback(() => {
        initTableSorting();
        setupFileInput();
        loadURLParams();
    });

    // 立即显示表格
    const dataTableSection = document.getElementById('dataTableSection');
    dataTableSection.style.display = 'block';
});

// 拆分初始化逻辑
function setupFileInput() {
    document.getElementById('fileInput').addEventListener('change', function(e) {
        const fileName = e.target.files[0] ? e.target.files[0].name : "选择CSV文件";
        document.querySelector('.custom-file-label').textContent = fileName;
    });
}

function loadURLParams() {
    const urlParams = new URLSearchParams(window.location.search);
    document.getElementById('filterUserId').value = urlParams.get('user_id') || '';
    document.getElementById('filterItemId').value = urlParams.get('item_id') || '';
    document.getElementById('filterBehaviorType').value = urlParams.get('behavior_type') || '';
}

// 初始化表格排序功能
function initTableSorting() {
    const table = document.getElementById('dataTable');
    const headers = table.querySelectorAll('th');
    let sortDirection = 1; // 1 for ascending, -1 for descending

    headers.forEach((header, index) => {
        if (header.querySelector('i')) {
            header.style.cursor = 'pointer';
            header.addEventListener('click', () => {
                // 重置所有排序图标
                headers.forEach(h => {
                    const icon = h.querySelector('i');
                    if (icon) icon.className = 'fas fa-sort';
                });

                // 设置当前排序方向
                const icon = header.querySelector('i');
                if (icon.className.includes('fa-sort-up')) {
                    icon.className = 'fas fa-sort-down';
                    sortDirection = -1;
                } else {
                    icon.className = 'fas fa-sort-up';
                    sortDirection = 1;
                }

                // 排序表格
                sortTable(table, index, sortDirection);
            });
        }
    });
}

// 表格排序函数
function sortTable(table, column, direction) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));

    rows.sort((a, b) => {
        const aValue = a.cells[column].textContent.trim();
        const bValue = b.cells[column].textContent.trim();

        // 尝试转换为数字比较
        if (!isNaN(aValue) && !isNaN(bValue)) {
            return (parseFloat(aValue) - parseFloat(bValue)) * direction;
        }

        // 字符串比较
        return aValue.localeCompare(bValue) * direction;
    });

    // 重新添加排序后的行
    rows.forEach(row => tbody.appendChild(row));
}

// 文件上传逻辑
document.getElementById('uploadForm').addEventListener('submit', function (event) {
    event.preventDefault();

    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    const progressBar = document.getElementById('uploadProgress');
    const progressBarInner = progressBar.querySelector('.progress-bar');

    if (!file) {
        showAlert('请选择一个文件', 'danger');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    // 显示进度条
    progressBar.style.display = 'block';
    progressBarInner.style.width = '0%';

    const xhr = new XMLHttpRequest();
    xhr.open('POST', "{{ url_for('ec.upload_file') }}", true);

    // 上传进度事件
    xhr.upload.addEventListener('progress', function(e) {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            progressBarInner.style.width = percentComplete + '%';
            progressBarInner.setAttribute('aria-valuenow', percentComplete);
        }
    });

    xhr.onload = function() {
        if (xhr.status === 200) {
            const data = JSON.parse(xhr.responseText);
            if (data.success) {
                showAlert(data.message, 'success');
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            } else {
                showAlert(data.message, 'danger');
            }
        } else {
            showAlert('文件上传失败', 'danger');
        }
        progressBar.style.display = 'none';
    };

    xhr.onerror = function() {
        showAlert('文件上传失败', 'danger');
        progressBar.style.display = 'none';
    };

    xhr.send(formData);
});

// 数据清洗逻辑
document.getElementById('cleanDataBtn').addEventListener('click', function () {
    const cleanedDataSection = document.getElementById('cleanedDataSection');
    const cleaningStatus = document.getElementById('cleaningStatus');
    const cleanDataBtn = this;

    // 显示加载状态
    cleanedDataSection.style.display = 'none';
    cleaningStatus.style.display = 'block';
    cleanDataBtn.disabled = true;
    cleanDataBtn.innerHTML = '<i class="now-ui-icons loader_refresh spin"></i> 正在清洗...';

    fetch('/clean_data', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
    })
    .then(response => response.json())
    .then(data => {
        const cleanedDataTable = document.getElementById('cleanedDataTable');
        cleanedDataTable.innerHTML = ''; // 清空之前的内容

        if (data.success && data.message) {
            // 如果没有错误数据，显示提示信息
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td colspan="5" class="text-center text-success">
                    <i class="now-ui-icons ui-1_check"></i> ${data.message}
                </td>
            `;
            cleanedDataTable.appendChild(tr);
        } else if (Array.isArray(data)) {
            // 如果有错误数据，展示错误数据
            data.forEach(row => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${row.user_id}</td>
                    <td>${row.item_id}</td>
                    <td>${row.category_id}</td>
                    <td>
                        <span class="badge badge-${row.behavior_type === 'pv' ? 'primary' : 
                            row.behavior_type === 'buy' ? 'success' : 
                            row.behavior_type === 'cart' ? 'warning' : 'info'}">
                            ${row.behavior_type === 'pv' ? '点击' : 
                             row.behavior_type === 'buy' ? '购买' : 
                             row.behavior_type === 'cart' ? '加购' : '收藏'}
                        </span>
                    </td>
                    <td>${row.timestamp}</td>
                `;
                cleanedDataTable.appendChild(tr);
            });
        }

        // 显示清洗结果
        cleaningStatus.style.display = 'none';
        cleanedDataSection.style.display = 'block';
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('数据清洗失败', 'danger');
    })
    .finally(() => {
        cleanDataBtn.disabled = false;
        cleanDataBtn.innerHTML = '<i class="now-ui-icons design_scissors"></i> 清洗数据';
    });
});

// 显示提示信息
function showAlert(message, type) {
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade show`;
    alert.role = 'alert';
    alert.innerHTML = `
        ${message}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    `;

    // 添加到页面顶部
    const content = document.querySelector('.content');
    content.insertBefore(alert, content.firstChild);

    // 5秒后自动消失
    setTimeout(() => {
        alert.classList.remove('show');
        setTimeout(() => alert.remove(), 150);
    }, 5000);
}